package com.lazy.utils.token.jwt;

import com.lazy.utils.interceptor.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: wangnan
 * @Description: jwt
 * @Date: Created in 15:20 2018/1/15
 */
@Slf4j
public class JWTHelper {
    private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();

    /**
     * 密钥加密token
     * @param id
     * @param phone
     * @param priKeyPath
     * @param expire
     * @return
     */
    public static String generateToken(Integer id, String phone, String priKeyPath, int expire)throws Exception  {
        log.info("密钥加密token,id:{},phone:{},priKeyPath:{},expire:{}",id,phone,priKeyPath,expire);
        String compactJws = Jwts.builder()
                .setSubject(phone)
                .claim("id", id)
                .setExpiration(DateTime.now().plusYears(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKeyPath))
                .compact();
        return compactJws;

    }
    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        log.info("公钥解析token,token:{},pubKeyPath:{}",token,pubKeyPath);
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
        return claimsJws;
    }

    /**
     * 获取token中的用户信息
     * @param token
     * @param pubKeyPath
     * @return
     */
    public static User getInfoFromToken(String token, String pubKeyPath) throws Exception {
        log.info("获取token中的用户信息:token:{},pubKeyPath:{}",token,pubKeyPath);
        Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
        Claims body = claimsJws.getBody();

        User user = new User();
        if(body.get("id") != null){
            user.setId((Integer)body.get("id"));
        }
        if("".equals(body.getSubject()) || body.getSubject() == null){
        }else {
            user.setName(body.getSubject());
        }
        log.info("解析出的token信息，user：{}",user.toString());
        return user;
    }

    /**
     * 生成公钥和私钥
     * @param pubKeyPath
     * @param priKeyPath
     * @param pass
     */
    public static void generateKey(String pubKeyPath, String priKeyPath, String pass){
        try {
            log.info("生成公钥和私钥,pubKeyPath:{},priKeyPath:{},pass:{}",pubKeyPath,priKeyPath,pass);
            rsaKeyHelper.generateKey(pubKeyPath,priKeyPath,pass);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
